package com.qdhh.enrollment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qdhh.enrollment.mapper.ProfileMapper;
import com.qdhh.enrollment.model.Profile;
import com.qdhh.enrollment.service.ProfileService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 档案服务实现类
 * 注意：根据文档设计，已移除所有审核相关逻辑
 */
@Service
public class ProfileServiceImpl extends ServiceImpl<ProfileMapper, Profile> implements ProfileService {

    @Override
    public Profile getByOpenid(String openid) {
        if (!StringUtils.hasText(openid)) {
            return null;
        }
        return getOne(new LambdaQueryWrapper<Profile>().eq(Profile::getOpenid, openid), false);
    }

    @Override
    public Profile upsertByOpenid(String openid, Profile patch) {
        if (!StringUtils.hasText(openid)) {
            return null;
        }

        Profile existing = getByOpenid(openid);
        LocalDateTime now = LocalDateTime.now();
        if (existing == null) {
            Profile toSave = Profile.builder()
                .openid(openid)
                .realName(patch.getRealName())
                .studentNo(patch.getStudentNo())
                .idCard(patch.getIdCard())
                .phone(patch.getPhone())
                .college(patch.getCollege())
                .major(patch.getMajor())
                .createdAt(now)
                .updatedAt(now)
                .build();
            save(toSave);
            return toSave;
        }
        if (StringUtils.hasText(patch.getRealName())) {
            existing.setRealName(patch.getRealName());
        }
        if (StringUtils.hasText(patch.getStudentNo())) {
            existing.setStudentNo(patch.getStudentNo());
        }
        if (StringUtils.hasText(patch.getIdCard())) {
            existing.setIdCard(patch.getIdCard());
        }
        if (StringUtils.hasText(patch.getPhone())) {
            existing.setPhone(patch.getPhone());
        }
        if (StringUtils.hasText(patch.getCollege())) {
            existing.setCollege(patch.getCollege());
        }
        if (StringUtils.hasText(patch.getMajor())) {
            existing.setMajor(patch.getMajor());
        }
        existing.setUpdatedAt(now);
        updateById(existing);
        return existing;
    }
}
